<?php

namespace app\common\controller;

use app\admin\model\ValidateCode;
use app\BaseController;
use think\Exception;
use think\facade\Cache;

/**
 * 华为云短信逻辑
 */
class Sms extends BaseController
{
    // 通知 + 普通验证码
    public static function send($tid, $mobile, $code = '')
    {
        try {
            // 1上午 2下午 3普通验证码 4疫苗异常 5核酸检测
            if (!in_array($tid, [1,2,3,4,5])) throw new Exception('验证码类型不存在');
            if (empty($mobile)) throw new Exception('手机号不存在');

            $url = config('sms.url');
            $APP_KEY = config('sms.app_key');
            $APP_SECRET = config('sms.app_secret');
            $TEMPLATE_ID = config('sms.template_id'.$tid);

            if ($tid == 3) {
                if (empty($code)) throw new Exception('六位数验证码不能为空');
                $signature = config('sms.signature2');
                $sender = config('sms.sender2');
                $TEMPLATE_PARAS = '["'.$code.'"]';
                $receiver = '+86'.$mobile;
            } else {
                $signature = config('sms.signature1');
                $sender = config('sms.sender1');
                $TEMPLATE_PARAS = '';
                foreach ($mobile as &$v) {
                    $v = '+86'.$v;
                }
                $receiver = implode(',', $mobile);
            }

            $headers = [
                'Content-Type: application/x-www-form-urlencoded',
                'Authorization: WSSE realm="SDP",profile="UsernameToken",type="Appkey"',
                'X-WSSE: ' . self::buildWsseHeader($APP_KEY, $APP_SECRET)
            ];

            $data = http_build_query([
                'from'              => $sender,
                'to'                => $receiver,
                'templateId'        => $TEMPLATE_ID,
                'templateParas'     => $TEMPLATE_PARAS,
                'statusCallback'    => '',
                'signature'         => $signature
            ]);

            $context_options = [
                'http' => ['method' => 'POST', 'header'=> $headers, 'content' => $data, 'ignore_errors' => true],
                'ssl' => ['verify_peer' => false, 'verify_peer_name' => false],
            ];

            $response = file_get_contents($url, false, stream_context_create($context_options));
            $response = json_decode($response, true);

            if (isset($response['code']) && $response['code'] == '00000') return 'success';
            return print_r($response, true);

        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    private static function buildWsseHeader(string $appKey, string $appSecret){
        date_default_timezone_set('Asia/Shanghai');
        $now = date('Y-m-d\TH:i:s\Z');
        $nonce = uniqid();
        $base64 = base64_encode(hash('sha256', ($nonce . $now . $appSecret)));
        return sprintf("UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"",
            $appKey, $base64, $nonce, $now);
    }
}